#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/Connector/lib -I/data/Software/mydan/Connector/private/lib
use strict;
use warnings;
use LWP::UserAgent;
use JSON;

$| ++;

=head1 SYNOPSIS

  #1
    cookie => 'MTUxNTAzMzg1NnxEdi1CQkFFQ180SUFBUXdCRUFBQU5mLUNBQUVGZEc5clpXNEdjM1J5YVc1bkRDSUFJREk0T1Rsa1l6aG1ZMk5tWWpRMk16TmtaV1kzTlRSbE1XWmtNVFpsTW1JeHyVJcLDk8iEGWlwsv8le0WzgNxhZ6JIYRFMOYzE8fKecA==',
    point => 'job_r'
    treeid => 123
  #3
    appname: xx
    appkey: xx

    return 1 if ok
=cut

my ( $pmspoint, %app, %env );
BEGIN{
    use Configini;
    $pmspoint = Configini::get( 'pmspoint' );
    %env = Configini::env( 'pmspointenv' );

    for my $file ( glob "/data/Software/mydan/*/conf/appname" )
    {
        my $name = `cat $file`;
        chomp $name;
        $file =~ s/appname/appkey/;
        my $key = `cat $file`;
        chomp $key;
        $app{$name} = $key eq 'c3random' && $ENV{OPEN_C3_RANDOM} ? $ENV{OPEN_C3_RANDOM} : $key;
    }

};

return sub
{
    my %param = @_;
    my ( $cookie, $point, $treeid ) = @param{qw(cookie point treeid )};

    if( $param{appname} && $param{appkey} )
    {
         return ( $app{$param{appname}} && $app{$param{appname}} eq $param{appkey} ) ? 1 : 0;
    }
    else
    {
        my $treestr = '';
        if( defined $treeid )
        {
            if( $treeid )
            {
                $treestr = "&treeid=$treeid";
            }
            else
            {
                if( $point =~ /_read$/ )
                {
                    return 1;
                }
                else
                {
                    $point =~ s/_read$/_root/;
                }
            }
        }

        my $ua = LWP::UserAgent->new;
        $ua->default_header( %env ) if %env;
        my $res = $ua->get( "$pmspoint?point=$point$treestr&cookie=$cookie" );
        unless( $res->is_success )
        {
             #TODO 确认上层调用是否捕获这个die
             die "call userauth.point fail";
        }
        my $data = eval{JSON::from_json $res->content};
        unless ( $data->{stat} ) {
            #TODO 确认上层调用是否捕获这个die
            die "call userauth.point result". $data->{info} || '';
        }
 
        return $data->{data};
    }
}

